<template>
  <div class="user-profile">
    <h2>个人主页</h2>
    <div class="profile-container">
      <div class="left-panel">
        <div class="user-profile-details">
          <img
            :src="'http://localhost:8080/images/upload/' + user.profile_picture"
            alt="头像"
            class="avatar"
          />
          <div class="user-info">
            <h3 class="user-name">{{ user.user_name }}</h3>
            <p class="user-gender">性别：{{ user.user_sex }}</p>
            <p class="user-follow-count">关注数：{{ followerCount }}</p>
            <p class="user-follower-count">粉丝数：{{ followingCount }}</p>
            <p class="user-location">地区：{{ user.country_region }}</p>
            <p class="user-status">状态：{{ user.user_status }}</p>
            <p class="user-label">听歌标签：{{ user.music_label }}</p>
            <p class="user-biography">{{ user.biography }}</p>
          </div>
        </div>
      </div>

      <div class="right-panel">
        <div class="query">
          <el-input
            placeholder="请输入笔记标题"

            v-model="queryStr"
            class="small-input"
            clearable
          ></el-input>
          <el-button size="small" round @click="queryInfo">查询</el-button>
        </div>

        <div class="user-notes">
          <h3>用户笔记</h3>
          <el-tabs v-model="activeName">
            <el-tab-pane label="已发布" name="first" @click="handleApprove">
              <p>共 {{ publishedNoteCount }} 条</p>
              <div class="note-grid">
                <div
                  class="note-card"
                  v-for="note in tableData"
                  :key="note.id"
                >
                  <div class="note-image">
                    <el-image
                      :src="'http://localhost:8080/images/upload/' + note.image"
                      style="width: 100%; height: 150px; cursor: pointer;"
                      @click="opennotedetail(note)"
                    ></el-image>
                  </div>


                  <div class="note-content">
                    <h4>{{ note.title }}</h4>
                    <div class="note-statistics">
                      <span>浏览量: {{ note.view_count }}</span>&nbsp;
                      <span>点赞量: {{ note.like_count }}</span>&nbsp;
                      <span>回复量: {{ note.comment_count }}</span>
                    </div>
                  </div>

                  <div class="note-timestamp">
                    <span>发布时间: {{ formatDate(note.create_time) }}</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      user_id: this.$route.params.user_id, // 路由传参
      user: {}, // 用户信息
      followerCount: 0, // 粉丝数
      followingCount: 0, // 关注数
      queryStr: "", // 查询输入框的内容
      activeName: "first", // 标签页激活状态
      tableData: [], // 存储已发布的笔记
      queryData: [], // 查询的笔记数据备份
      publishedNoteCount: 0, // 已发布笔记数量
    };
  },
  mounted() {
    this.userId = this.$route.params.user_id; // 从路由参数中获取 userId,在 Vue 路由中获取参数
    this.fetchUserInfo();
    this.fetchFollowerCount();
    this.fetchFollowingCount();
    this.fetchPublishedNoteCount();
    this.getAllPublishedNotes();
  },
  methods: {
    // 格式化日期时间
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 查询笔记
    queryInfo() {
      if (this.queryStr.trim()) {
        this.tableData = this.queryData.filter(item =>
          item.title.includes(this.queryStr.trim())
        );
      } else {
        this.tableData = [...this.queryData]; // 重置数据
      }
    },

    // 获取已发布笔记
    getAllPublishedNotes() {
      axios
        .get("/v1/NoteCreateinfo1", {
          params: { note_status: "审核通过", user_id: this.user_id },
        })
        .then(response => {
          this.tableData = response.data.list;
          this.queryData = this.tableData;
          console.log("笔记数据:", this.tableData);
        });
    },

    // 获取发布笔记的总数
    fetchPublishedNoteCount() {
      axios
        .get(`/v1/NoteCreate/count`, {
          params: { note_status: "审核通过", user_id: this.user_id },
        })
        .then(response => {
          this.publishedNoteCount = response.data;
        });
    },

  //进入笔记详情页面
  opennotedetail(note){
    sessionStorage.setItem('note_create_id', note.note_create_id);
    this.navigateTo('/note-detail', note);
  },


    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await axios.get(
          `http://localhost:8080/v1/Userinfo/${this.user_id}`
        );
        this.user = response.data;
      } catch (error) {
        console.error("获取用户信息失败", error);
        ElMessage.error("获取用户信息失败");
      }
    },

    // 获取粉丝数
    async fetchFollowerCount() {
      try {
        const response = await axios.get(
          `http://localhost:8080/user/${this.user_id}/followers/count`
        );
        this.followerCount = response.data;
      } catch (error) {
        console.error("获取粉丝数失败", error);
        ElMessage.error("获取粉丝数失败");
      }
    },

    // 获取关注数
    async fetchFollowingCount() {
      try {
        const response = await axios.get(
          `http://localhost:8080/user/${this.user_id}/following/count`
        );
        this.followingCount = response.data;
      } catch (error) {
        console.error("获取关注数失败", error);
        ElMessage.error("获取关注数失败");
      }
    },

    highlightQuery(text) {
  const query = this.queryStr.trim();
  if (!query) return text;
  return text.replace(new RegExp(`(${query})`, 'gi'), '<mark>$1</mark>');
},


    navigateTo(route) {  
      this.$router.push(route); // 使用路由跳转  
    },

    handleApprove() {
      this.getAllPublishedNotes();
    },
  },
};
</script>

<style scoped>
.user-profile {
  font-family: 'KaiTi', serif;
  background: linear-gradient(to right, #f9f4e8, #e8dfca);
  color: #4b3f33;
  padding: 20px;
}

/* 布局容器 */
.profile-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

/* 左侧用户信息栏 */
.left-panel {
  flex: 1;
  max-width: 25%;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-profile-details {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #d6c8b0;
}

.user-info p {
  margin: 10px 0;
}

/* 右侧笔记区域 */
.right-panel {
  flex: 3;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 搜索栏样式 */
.query {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.small-input {
  width: 200px;
  margin-right: 10px;
}

/* 笔记网格 */
.note-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 一行放三个笔记 */
  gap: 15px; /* 调整间隔大小 */
}

.note-card {
  border: 1px solid #e0e0e0;
  border-radius: 6px; /* 稍微缩小圆角 */
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* 轻微阴影 */
  overflow: hidden;
}

.note-image {
  width: 100%;
}

.note-content {
  padding: 10px;
}

.note-content h4 {
  margin: 0 0 10px;
  font-size: 1.1rem;
  color: #4b3f33;
}

.note-statistics span {
  font-size: 0.9rem;
  color: #7d7164;
}

.note-timestamp {
  text-align: right;
  font-size: 0.8rem;
  color: #a38f73;
  padding: 5px 10px;
}
</style>

